<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;


use app\api\model\ChimiEvent;
use app\api\model\ChimiEventV3;
use app\api\model\ChimiMaterial;
use app\api\model\ChimiMaterialDetails;
use app\api\model\ChimiZimuEvent;
use app\api\model\LinUser;
use app\api\model\LiveMajor;
use app\api\model\LiveVoice;
use app\api\model\LiveXuanp;
use app\api\model\Upload;
use app\api\model\VideoProductMaterial;
use app\api\service\token\LoginToken;
use think\Request;
use think\Db;
use think\Exception;

class Chimi
{
    public function daily(Request $request)
    {
        // 允许所有域访问
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        $start_time = $request->get()['start_time'];
        $end_time = $request->get()['end_time'];
        $result = LiveMajor::field('sum(fukje) as total_fukje, count(id) as sale_num,platform,chudqd,source')
            ->where('fuksj','>=',$start_time)
            ->where('fuksj','<=',$end_time)
            ->group('platform,chudqd,source')
            ->select();
        return  writeJson(200,$result , '首页明细');

    }

    public function show(Request $request)
    {
        // 允许所有域访问
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

        $start_time = $request->get()['start_time'];
        $end_time = $request->get()['end_time'];
        $arr = [];
        // 总计销售金额 订单量
        $item = LiveMajor::field('sum(fukje) as total_fukje,max(id) as total_order_num')->find();
        $arr['total_fukje'] = $item['total_fukje'];
        $arr['total_order_num'] = $item['total_order_num'];

        // 累计服务品牌 根据店铺名称统计
        $arr['total_pinpai_count'] =  LiveMajor::count('DISTINCT dianpmc');

        // 团购商品订单排名
        $arr['tg_products'] = LiveMajor::field('shangpbt, count(id) as sale_num')
            ->where('source','团购')
            ->group('shangpbt')
            ->order('sale_num', 'desc')
            ->limit(20)
            ->select();

        // 电商店铺按照销售额排序
        $arr['ds_shops'] = LiveMajor::field('dianpmc, sum(fukje) as total_fukje, count(id) as sale_num')
            ->group('dianpmc')
            ->where('source','电商')
            ->order('sale_num', 'desc')
            ->limit(20)
            ->select();


        // 电商按照月份来
        $arr['ds_months'] = LiveMajor::field("DATE_FORMAT(fuksj, '%m') as month,sum(fukje) as total_sales")
            ->where('source','电商')
            ->group('month')
            ->select();


        // 电商按照月份来
        $arr['tg_months'] = LiveMajor::field("DATE_FORMAT(fuksj, '%Y-%m') as month")
            // 计算每月销售额总和
            ->field('count(id) as sale_num')
            ->where('source','团购')
            // 按月份分组
            ->group('month')
            ->select();

        $arr['ds_platforms'] = LiveMajor::field("platform")->where('source','电商')
            // 计算每月销售额总和
            ->field('SUM(fukje) as total_sales')
            // 按月份分组
            ->group('platform')
            ->select();

        $arr['tg_platforms'] = LiveMajor::field("platform")
            ->where('source','团购')
            // 计算每月销售额总和
            ->field('count(id) as sale_num')
            // 按月份分组
            ->group('platform')
            ->select();

        $arr['ds_products'] = LiveMajor::field('shangpbt')
            ->where('source','电商')
            ->order('fuksj', 'desc')
            ->limit(50)
            ->select();

        return  writeJson(200,$arr , '首页报表');

    }


    public function editXuanp(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $item = LiveXuanp::where('id',$params['id'])->find();
        if(!empty($params['remark'])){
            $item->remark = $params['remark'];
            $item->uid = $uid;
            $item->save();
        }
        return  writeJson(200,$item , '编辑选品');

    }


    /*
     * 爆品选品清单
     * */
    public  function xuanp(Request $request)
    {
        $params = $request->get();
        $subQuery = LiveXuanp::field([
                'round(sale_num/tuig) as sn',
                'round(sale_num*video_rate/video_relation) as video_avg',
                'pid', 'pname', 'sale_num','search_key','remark','id',
                'video_relation', 'tuig', 'price', 'link','img'
            ])
            ->where('tuig', '>', 10)
            ->where('sale_num', '>', 1000)
            ->where('price', '>', 20)
            ->where('video_relation', '>', 10)
            ->having('round(sale_num/tuig) > 50')
            ->buildSql();

        // 2. 对子查询结果进行分页
        $result = Db::table($subQuery . ' a')
            ->order('a.sn', 'desc')
            ->paginate(50); // 这里的分页就不会受having影响了

        return  writeJson(200,$result , '爆款选品');
    }

    public function addXuanp(Request $request)
    {
        $params = $request->post();
        $count = 0;
        foreach ($params['data'] as $item){
            $m = LiveXuanp::where('pid',$item['pid'])->findOrEmpty();
            if($m->isEmpty()){
               LiveXuanp::create($item);
               $count++;
            }

        }

        return  writeJson(200,$count , '选品新增');

    }

    public function addMaterial(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $m = ChimiMaterial::where('content_id',$params['content_id'])->findOrEmpty();

        if($params['is_rand'] == 0){
            if(empty($params['start_point'])){
                return  writeJson(400,0 , '标注下开始和结束秒数');
            }
        }
        if(!$m->isEmpty()){
            return  writeJson(400,0 , '已存在');
        }
        $params['uid'] = $uid;
        $params['threshold'] = 5.0;
        $params['min_duration'] = 3;
        $params['max_duration'] = 7;
        $res = ChimiMaterial::create($params);

        return  writeJson(200,$res , '素材新增');
    }


    // 根据名字获取主播模型
    public function getMaterialsByUser(Request $request)
    {
        $uname = $request->get()['uname'];

        $user = LinUser::where('username',$uname)->findOrEmpty();
        if($user->isEmpty()){
            return  writeJson(200,null , '用户不存在');
        }


        $item = ChimiMaterial::where('uid',$user['id'])->where('status',1)->findOrEmpty();
        if(!$item->isEmpty()){

            $item->status = 2;
            $item->get_time = date('Y-m-d H:i:s');
            $item->save();

        }

        return  writeJson(200,$item , '素材获取');
    }



    public function addMaterialDetails(Request $request)
    {
        $params = $request->post()['data'];

        $uid = LoginToken::getInstance()->getCurrentUid();

        $datas = [];
        foreach ($params as $param){

            $param['uid'] = $uid;
            $datas[] = $param;
        }

        $res = ChimiMaterialDetails::insertAll($datas);

        return  writeJson(200,$res , '素材新增');
    }

    public function addEvent(Request $request) {
        $params = $request->post();
        $event = new ChimiEvent();
        DB::startTrans();
        try {
            $ids = [];
            $uid = LoginToken::getInstance()->getCurrentUid();
            $username = LoginToken::getInstance()->getCurrentUserName();

            $params['uid'] = $uid;
            $params['model'] = $username;
            $params['status'] = 1;
            $params["zimu_site"] = 30;
            $params["zimu_size"] = 10;
            $params["zimu_style"] = "style1";

            $script_arr = json_decode($params["script"], true);
            $params["is_kou"] = 0;

            // 如果没有指定sound_model 则随机一个
            if (!isset($params["sound_model"]) || empty($params["sound_model"])) {
                $sound = LiveVoice::whereNotNull("boba_voice")->orderRand()->findOrEmpty();
            } else {
                $sound = LiveVoice::where("guang_model", $params["sound_model"])->findOrEmpty();
            }
            $params["sound_model"] = $sound["boba_voice"];

            foreach ($script_arr as $key=>$val) {
                // 检查视频链接
                if (empty($val["url"])) {
                    throw new Exception("第" . ($key + 1) . "个视频链接为空");
                }
                if (strpos($val["text"], "直播") !== false) {
                    throw new Exception( "字幕" . ($key + 1) . "含有敏感词-直播");
                }
                $script_arr[$key]["text"] = str_replace("、", ",", $val["text"]);
//                if (strpos($val["url"], "mp4") === false) {
//                    throw new Exception("第" . ($key + 1) . "个视频未上传结束（".$val["url"]."）");
//                }

                if ($val["is_kou"] == 1) {
                    $params["is_kou"] = 1;
                    $params["status"] = 11;
                }

                //拿取position
                if ($val["ma_id"] == 0) {
                    $script_arr[$key]["position"] = null;
                } else {
                    $ma_info = VideoProductMaterial::where("id", $val["ma_id"])->findOrEmpty();
                    $script_arr[$key]["position"] = $ma_info["position"];
                }
            }
            $params["script"] = json_encode($script_arr, JSON_UNESCAPED_SLASHES  | JSON_UNESCAPED_UNICODE);
            $new = $event->create($params);

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,$e->getMessage());
        }
        return writeJson(200, $new, '请求成功');
    }

    public function getVideoEvent(Request $request) {
        $event = new ChimiEvent();
        $info_query = $event->where("status", 1)
            ->where("is_top", 1)
            ->where(function ($q){
                $ten_min_ago = date("Y-m-d H:i:s", time() - 300);
                $q->whereNull('get_time')->whereOr('get_time','<',$ten_min_ago);
            });
        $info = $info_query->findOrEmpty();
        if ($info->isEmpty()) {
            $info_query = $info_query->removeWhereField("is_top");
            $info = $info_query->findOrEmpty();
        }

        if (!$info->isEmpty()) {

            if ($info["is_kou"] == 1) {
                // 检查口型配好没
                $upload = Upload::where("main_task_id", $info["id"])->whereNull("qiniu")->count();
                if ($upload == 0) {
                // 配好了
                    $upload_info = Upload::where("main_task_id", $info["id"])->select()->toArray();
                } else {
                    $info->get_time = date("Y-m-d H:i:s", time());
                    $info->save();
                    return writeJson(200, [], '无');
                }
            }

            $json_script = json_decode($info["script"], true);
            foreach ($json_script as &$s) {
                if (!empty($upload_info)) {
                    foreach ($upload_info as $u) {
                        if ($s["id"] == $u["number"]) {
                            $s["url"] = $u["qiniu"];
                            $s["audio"] = $u["product_audio_url"];
                        }
                    }
                }
            }

            $info->status = 2;
            $info->get_time = date("Y-m-d H:i:s", time());
            $info->save();
            $info["script"] = json_encode($json_script);
            return writeJson(200, $info, '请求成功');

        } else {
            return writeJson(200, [], '无');
        }
    }

    public function backfillEvent(Request $request)
    {
        $params = $request->post();
        $info = ChimiEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->save($params);
            return writeJson(200,$info,'成功！');
        } else {
            return writeJson(400,[],'找不到！');
        }
    }

    public function getOrderEvent()
    {
        $event = new ChimiEvent();
        $info = $event->where("status", 11)->where("is_top", 1)->findOrEmpty();
        if ($info->isEmpty()) {
            $info = $event->where("status", 11)->findOrEmpty();
        }
        if (!$info->isEmpty()) {
            $info->status = 12;
            $info->save();
            return writeJson(200, $info, '请求成功');
        } else {
            return writeJson(200, [], '无');
        }
    }

    public function list(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $event = new ChimiEvent();

        $query = $event->field("*");

        if ($uid != 1) {
            $query = $query->where("uid", $uid);
        }
//        if (!empty($params["pid"])) {
//            $query = $query->whereLike("pid", "%".$params["pid"]."%");
//        }
//        if (!empty($params["pname"])) {
//            $query = $query->whereLike("pname", "%".$params["pname"]."%");
//        }
        if (!empty($params["model"])) {
            $query = $query->whereLike("model", "%".$params["model"]."%");
        }
//        if (!empty($params["type"])) {
//            $query = $query->where("type", $params["type"]);
//        }
        if (!empty($params["check"])) {
            $query = $query->where("check", $params["check"]);
        }
        if (!empty($params["status"])) {
            $query = $query->where("status", $params["status"]);
        }
//        if (!empty($params["secondary"])) {
//            $query = $query->where("category", $params["secondary"]);
//        }
//        if (!empty($params["secondary"])) {
//            $query = $query->where("b.secondary", $params["secondary"]);
//        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("create_time", "<", $params["end_time"]);
        }
//        if (!empty($params["jd_export"])) {
//            if ($params["jd_export"] == 1) {
//                $query = $query->where("jd_export", $params["jd_export"]);
//            } else {
//                $query = $query->whereNull("jd_export");
//            }
//        }
//        if (!empty($params["tb_export"])) {
//            if ($params["tb_export"] == 1) {
//                $query = $query->where("tb_export", $params["tb_export"]);
//            } else {
//                $query = $query->whereNull("tb_export");
//            }
//        }
        $list = $query->order("id desc")->paginate($pageSize);

        $download = $query->removeOption("field")->removeOption("order")
            ->field("count(*) c")
            ->where("dy_export", 1)->select();
        $list["download"] = $download[0]["c"];
        return writeJson(200,$list,'数据列表！');

    }

    public function resetEvent(Request $request)
    {
        $params = $request->get();
        $info = ChimiEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            if ($info["status"] == 14) {
                $info->status = 11;
            }
            if ($info["status"] == 4) {
                $info->status = 1;
            }
            if ($info["status"] == 3) {
                Upload::where("main_task_id", $info["main_task_id"])->delete();
                $info->status = 11;
            }
            $info->save();
        }
        return writeJson(200, true, '请求成功');

    }

    public function signDownload(Request $request)
    {
        $params = $request->get();
        $info = ChimiEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            if ($info["dy_export"] == null) {
                $info->dy_export = 1;
                $info->dy_backtime = date('Y-m-d H:i:s');
            }
            $info->save();
        }
        return writeJson(200, true, '请求成功');
    }

    public function getListById(Request $request)
    {
        $params = $request->get();
        $fifteenDaysAgo = strtotime('-15 days', time());
        $two_hour_ago = date("Y-m-d H:i:s", time() - 3600);

        DB::startTrans();
        try {
            $event = new ChimiEvent();
            $uid = LoginToken::getInstance()->getCurrentUid();

            if ($uid != 1) {
                throw new Exception("无权限");
            }
            if (!isset($params["dy"]) || !isset($params["tb"])) {
                throw new Exception("请更换新版本插件");
            }
            if (!isset($params["limit"])) {
                throw new Exception("未选择数量");
            }

            $list_query = $event->where("status", 3);
            if (isset($params["model"]) && !empty($params["model"])) {
                $list_query = $list_query->where("model", $params["model"]);
            }
            if ($params["tb"] == "是") {
                $list_query = $list_query
                    ->where('tb_export', 'null')
                    ->where(function ($q) use ($two_hour_ago){
                        $q->whereNull('tb_get_time')->whereOr('tb_get_time','<',$two_hour_ago);
                    });
            }
            $list_query = $list_query->where("get_time", ">=", date('Y-m-d H:i:s', strtotime('midnight', $fifteenDaysAgo)));

            if ($params["limit"] != 0) {
                $list_query = $list_query->limit($params["limit"]);
            }
            $list = $list_query->lock()->select()->toArray();

            // 被领取到的 先标记时间 并检查标题重复性
            $titles = [];
            $savedata = [];
            if (!empty($list)) {
                foreach ($list as $li) {
                    $item = [];
                    $item["id"] = $li["id"];
                    if (in_array($li["title"], $titles)) {
                        $item["same_title"] = 1;
                    } else {
                        $titles[] = $li["title"];
                        $item["same_title"] = 0;
                        if ($params["tb"] == "是" && $li["tb_export"] == null) {
                            $item["tb_get_time"] = date("Y-m-d H:i:s");
                        }
                    }

                    $savedata[] = $item;
                }
                $res = $event->saveall($savedata);
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e->getMessage(), '请求失败', 20001);
        }

        return writeJson(200, $list, '请求成功');

    }


    //==============================3.0====================================

    public function videoToZimu(Request $request){
        $params = $request->post();

        $port = 5000;
//        if (isset($_COOKIE["cur_videoToZimu_index"])) {
//            $cur_index = $_COOKIE["cur_videoToZimu_index"];
//            $cur_index = intval($cur_index);
//            $cur_index += 1;
//            if ($cur_index > 1) {
//                $cur_index = 0;
//            }
//        } else {
//            $cur_index = 0;
//        }
//        $port += $cur_index;
//        setcookie("cur_videoToZimu_index", $cur_index, time()+3600);
        $url = "http://127.0.0.1:".strval($port)."/videoToZimu";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));// 文本提交方式，必须声明请求头
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output);
    }

    /**
     * @param Request $url
     * @return \think\response\Json
     */
    public function addImageEvent(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $params["uid"] = $uid;

        $result = ChimiZimuEvent::create($params);
        return writeJson(200,$result["id"],'完成！');
    }

    /**
     * @param('id','ID','require')
     */
    public function checkImgEvent(Request $request)
    {
        $params = $request->get();

        $event = ChimiZimuEvent::where("id", $params["id"])->findOrEmpty();
        if ($event->isEmpty()) {
            return writeJson(200,[],'任务不存在！');
        }
        $return = [
            "zimu" => $event["zimu"],
            "status" => $event["status"],
            "reason" => $event["reason"]
        ];
        return writeJson(200,$return,'完成！');
    }


    public function getImgEvent()
    {
        $event = ChimiZimuEvent::where('status', 1)->findOrEmpty();
        if ($event->isEmpty()){
            return writeJson(200,[],'暂无！');
        }
        $res = $event->save(["status"=>2], ["id"=>$event['id']]);

        return writeJson(200,$event,'完成！');
    }

    /**
     * @param('id','ID','require')
     */
    public function backFillImg(Request $request)
    {
        $params = $request->post();

        $info = ChimiZimuEvent::where("id",$params["id"])
            ->where("status", 2)->findOrEmpty();
        if ($info->isEmpty()) {
            return writeJson(200,[],'任务不存在！');
        }
        $result = $info->save($params,["id"=>$info['id']]);
        return writeJson(200,$result,'完成！');
    }

    public function addEventNew(Request $request) {
        $params = $request->post();
        $event = new ChimiEventV3();
        DB::startTrans();
        try {
            $ids = [];
            $uid = LoginToken::getInstance()->getCurrentUid();
            $username = LoginToken::getInstance()->getCurrentUserName();

            $params['uid'] = $uid;
            $params['model'] = $username;
            $params['status'] = 1;
            $params["zimu_site"] = 30;
            $params["zimu_size"] = 10;
            $params["zimu_style"] = "style1";

            $script_arr = json_decode($params["script"], true);
            $params["is_kou"] = 0;

            //todo
            // 如果没有指定sound_model 则随机一个
            if (!isset($params["sound_model"]) || empty($params["sound_model"])) {
                $sound = LiveVoice::whereNotNull("boba_voice")->orderRand()->findOrEmpty();
            } else {
                $sound = LiveVoice::where("guang_model", $params["sound_model"])->findOrEmpty();
            }
            $params["sound_model"] = $sound["boba_voice"];

            foreach ($script_arr as $key=>$val) {
                // 检查视频链接
                if (empty($val["url"])) {
                    throw new Exception("第" . ($key + 1) . "个视频链接为空");
                }
                if (strpos($val["text"], "直播") !== false) {
                    throw new Exception( "字幕" . ($key + 1) . "含有敏感词-直播");
                }
                $script_arr[$key]["text"] = str_replace("、", ",", $val["text"]);
//                if (strpos($val["url"], "mp4") === false) {
//                    throw new Exception("第" . ($key + 1) . "个视频未上传结束（".$val["url"]."）");
//                }

                if ($val["is_kou"] == 1) {
                    $params["is_kou"] = 1;
                    $params["status"] = 11;
                }

                // 存素材
                if ($val["is_cun"] == 1) {
                    $material = [
                        "uid"=>$uid,
                        "douyin_pid"=>$params["pid"],
                        "douyin_pname"=>$params["pname"],
                        "url"=>$val["url"],
                        "use_num"=>1
                    ];
                    ChimiMaterial::create($material);
                }
            }
            $params["script"] = json_encode($script_arr, JSON_UNESCAPED_SLASHES  | JSON_UNESCAPED_UNICODE);
            $new = $event->create($params);

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,$e->getMessage());
        }
        return writeJson(200, $new, '请求成功');
    }

    public function getOrderEventV3()
    {
        $event = new ChimiEventV3();
        $info = $event->where("status", 11)->where("is_top", 1)->with("zimu")->findOrEmpty();
        if ($info->isEmpty()) {
            $info = $event->where("status", 11)->with("zimu")->findOrEmpty();
        }
        if (!$info->isEmpty()) {
            $info->status = 12;
            $info->save();
            return writeJson(200, $info, '请求成功');
        } else {
            return writeJson(200, [], '无');
        }
    }

    public function backfillEventV3(Request $request)
    {
        $params = $request->post();
        $info = ChimiEventV3::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->save($params);
            return writeJson(200,$info,'成功！');
        } else {
            return writeJson(400,[],'找不到！');
        }
    }
}